<?php
/**
 * 控制器过滤器
 *
 * @package if
 * @subpackage util.filter.action
 * @since 1.0
 */
class IControllerAttrFilter extends IActionFilter  {
	private $attrs;
	
	/**
	 * Enter description here...
	 *
	 * @param IController $controller
	 */
	function _before(&$controller) {
		$this->attrs = $controller->attrs();
		extract($this->attrs);
		
		//不能被执行
		if (isset($_private) && $_private) {
			throw new IException("the controller is private", 0x100032);
		}
		
		//只能在命令行下执行
		if (isset($_protected) && $_protected && !IRequest::singleton()->isCli()) {
			throw new IException("the controller is protected", 0x100033);
		}
		
		//在特定env下才能执行
		if (isset($_env)) {
			if (!is_array($_env)) {
				$_env = preg_split("/\s*,\s*/s", $_env);
			}
			if (!in_array(IF_APP_ENV, $_env)) {
				throw new IException("the controller can only run under " . implode(", ", $_env) . " environment", 0x100034);
			}
		}
		
		//缓存动作
		if (isset($_cacheAction) && $controller->action()->match($_cacheAction)) {
			if (!IApplication::hasModule("cache")) {
				$this->_log("before using '_cacheAction', cache module must be loaded", ILog::LOG_WARNING);
				return;
			}
			ob_start();
			$engine = ICache::engine(o("@cache.default"));
			$cached = $engine->entry("cacheAction:" . $controller->name() . "." . $controller->action()->name());
			$controllerFile = $controller->file();
			if (!is_null($cached) && (!$controllerFile || filemtime($controllerFile) < $cached->modified())) {
				echo $cached->value();
				return false;
			}
		}
		
		//缓存页面
		if (isset($_cachePage) && $controller->action()->match($_cachePage)) {
			if (!IApplication::hasModule("cache")) {
				$this->_log("before using '_cachePage', cache module must be loaded", ILog::LOG_WARNING);
				return;
			}
			ob_start();
			$engine = ICache::engine(o("@cache.default"));
			$cached = $engine->entry("cachePage:" . __URI__);
			$controllerFile = $controller->file();
			if (!is_null($cached) && (!$controllerFile || filemtime($controllerFile) < $cached->modified())) {
				echo $cached->value();
				return false;
			}
		}
	}
	
	function _after(&$controller) {
		extract($this->attrs);
		
		//缓存动作
		if (isset($_cacheAction) && $controller->action()->match($_cacheAction)) {
			if (!IApplication::hasModule("cache")) {
				$this->_log("before using '_cacheAction', cache module must be loaded", ILog::LOG_WARNING);
				return;
			}
			$engine = ICache::engine(o("@cache.default"));
			$engine->write("cacheAction:" . $controller->name() . "." . $controller->action()->name(), ob_get_contents());
		}
		
		//缓存页面
		if (isset($_cachePage) && $controller->action()->match($_cachePage)) {
			if (!IApplication::hasModule("cache")) {
				$this->_log("before using '_cachePage', cache module must be loaded", ILog::LOG_WARNING);
				return;
			}
			$engine = ICache::engine(o("@cache.default"));
			$engine->write("cachePage:" . __URI__, ob_get_contents());
		}
	}
}

?>